<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/7/16 13:36
 * Modified Time: 2019/7/16 13:36
 * Version: 2.0
 */

namespace App\Modules\Store\Criterias;


use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;
use Illuminate\Support\Facades\DB;

class GetStoreListCriteria extends BaseCriterias
{
    private $user_lng;
    private $user_lat;
    private $adcode;
    private $orderBy;
    private $keywords;

    public function __construct($user_lng, $user_lat,$adcode, $orderBy, $keywords)
    {
        $this->user_lng = $user_lng;
        $this->user_lat = $user_lat;
        $this->adcode = $adcode;
        $this->orderBy = $orderBy;
        $this->keywords = $keywords;
    }

    public function apply($model, RepositoryInterface $repository)
    {
        $user_lat = $this->user_lat;
        $user_lng = $this->user_lng;
        $adcode = substr($this->adcode,0,3);
        $orderBy = $this->orderBy;
        $keywords = $this->keywords;

        if ($orderBy == 1) {
            $orderBy = 'distance';
            $orderBySC = 'ASC';
        } else {
            $orderBy = 'score';
            $orderBySC = 'DESC';
        }

        $comment_query = DB::table('order_comment')
            ->selectRaw('score_store,avg(waiting_time) as waiting_time,store_id')
            ->groupBy('store_id');

        $service_query = DB::table('store_service')
            ->selectRaw('count(*) as store_service_num,min(price) as price,store_id')
            ->groupBy('store_id');

        $store_resource_query = DB::table('store_resource')
            ->selectRaw('count(*) as store_resource_num,store_id')
            ->where('type',1)
            ->groupBy('store_id');


        $select = [
            'hx_store.id',
            'hx_store.name',
            'hx_picture.image',
            'hx_store.level',
            'hx_store.order_sum',
            'lat_lng_distance(' . $user_lat . ',' . $user_lng . ',hx_store.latitude,hx_store.longitude) as distance',
            'IFNULL(price,0) as price',
            'IFNULL(hx_comment.waiting_time,0) as waiting_time'
        ];
        $select = implode($select, ',');

        $model = $model->selectRaw($select)
            ->leftJoin('picture', 'store.logo', 'picture.id')
            ->leftJoin(\DB::raw("({$comment_query->toSql()}) as hx_comment"), function ($join) use ($comment_query) {
                $join->mergeBindings($comment_query)->on('store.id', '=', 'comment.store_id');
            })
            ->leftJoin(\DB::raw("({$service_query->toSql()}) as hx_service"), function ($join) use ($service_query) {
                $join->mergeBindings($service_query)->on('store.id', '=', 'service.store_id');
            })
            ->leftJoin(\DB::raw("({$store_resource_query->toSql()}) as hx_store_resource"), function ($join) use ($store_resource_query) {
                $join->mergeBindings($store_resource_query)->on('store.id', '=', 'store_resource.store_id');
            })
            ->with(['storeResource' => function ($query) {
                $select = [
                    'hx_store_resource.id',
                    'hx_store_resource.store_id',
                    'hx_store_resource.resource',
                    'type',
                    'CASE WHEN type = 1 THEN hx_picture.image else hx_video.thumb END as image',
                    'CASE WHEN type = 1 THEN null else hx_video.url END as video',
                ];
                $select = implode($select, ',');

                $query->selectRaw($select)
                    ->leftJoin('picture', function ($join) {
                        $join->on('store_resource.resource', '=', 'picture.id');

                    })
                    ->leftJoin('video', function ($join) {
                        $join->on('store_resource.resource', '=', 'video.id');

                    });
            }])
            ->when($keywords, function ($query) use ($keywords) {
                $query->where('store.name', 'like', '%' . $keywords . '%');
            })
            ->where('store.adcode','like',$adcode."%")
            ->where('store_resource.store_resource_num','>=',3)
            ->where('service.store_service_num','>=',1)
            ->orderBy($orderBy, $orderBySC)
        ;
        return $model;

    }
}